﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Model;
using BLL;
using System.Net.Http;
using System.Text;
using System.Configuration;
using Newtonsoft.Json;


namespace TrainManage.Controllers
{
    public class HomeController : Controller
    {

        public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];


        #region 登录、注册、首页

        UserInfoBll bll = new BLL.UserInfoBll();


        /// <summary>
        /// 初始化登录页面
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginPage()
        {
            return View();
        }

        /// <summary>
        /// 实现登录功能
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginDo()
        {
            string name = Request["UserName"].ToString();
            string pwd = Request["UserPwd"].ToString();
            UserInfo user = bll.ShowUserInfo().Where(s => s.UserName == name & s.UserPwd == pwd).FirstOrDefault();
            if (user != null)
            {
                if (Request["yzm"].ToUpper().ToString() == Session["CheckCode"].ToString().ToUpper())
                {
                    Session["UserName"] = user.UserName;
                    Session["RoleId"] = user.RoleId;
                    return View("DefaultPage");
                }
                else
                {
                    return Content("<script>alert('验证码输入有误');location.href='/Home/LoginPage'</script>");
                }
            }
            else
            {
                return Content("<script>alert('登录失败')</script>");
            }
        }
        public ActionResult TuiChu()
        {
            Session["UserName"] = null;
            Response.Redirect("/Home/LoginPage");
            return View();
        }

        /// <summary>
        /// 初始化注册页面
        /// </summary>
        /// <returns></returns>
        public ActionResult RegisterPage()
        {
            return View();
        }
        /// <summary>
        /// 实现注册功能
        /// </summary>
        /// <param name="n1"></param>
        /// <returns></returns>
        [HttpPost]
        public int Register(UserInfo n1)
        {

            n1.CreateDate = Convert.ToDateTime(DateTime.Now.ToString());
            n1.RoleId = 2;
            BLL.UserInfoBll bll = new BLL.UserInfoBll();
            var name = Request["UserName"];

            
            if (bll.SeleName().Where(a=>a.UserName==name).Count()>0)
            {
                return -5;
            }
            else
            {
                if (Request["mobile"].ToString() == Session["Mobile"].ToString())
            {

                if (bll.Register(n1))
                {

                    return 1;
                }

                else
                {
                    return -1;
                }
            }
            else
            {
                return -3;
            }
          }


        }



        /// <summary>
        /// 获取手机 验证码
        /// </summary>
        /// <param name="mobiles"></param>
        /// <returns></returns>
        public string PhoneYzm(string mobiles)
        {
            if (mobiles != null)
            {
                string account = "C89849067";//用户名是登录ihuyi.com账号名（例如：cf_demo123）
                string password = "e77161ae8c360f93ab0d3a79f5c94ea0"; //请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
                string mobile = mobiles;
                Random rad = new Random();//生成随机数
                int mobile_code = rad.Next(1000, 10000);
                             string content = "您的验证码是：" + mobile_code + " 。请不要把验证码泄露给其他人。";//要发送的内容
                Session["Mobile"] = mobile;

                string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}&format={4}";//拼接字符串形成请求体
                using (HttpClient client = new HttpClient())//用客户端请求API数据
                {
                    //进行utf-8进行编码解析；因为API接口需要密文以字节数组的形式发送
                    UTF8Encoding encoding = new UTF8Encoding();
                    //将请求体编码成字节数组
                    byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content, "json"));
                    //设置请求体
                    HttpContent contents = new ByteArrayContent(postData, 0, postData.Length);
                    //设置请求头（标头）成字节数组
                    contents.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    //请求结果
                    var result = client.PostAsync(PostUrl, contents).Result;
                    //判断请求结果的状态码
                    if (result.IsSuccessStatusCode)
                    {
                        //返回的json结果
                        var jj = result.Content.ReadAsStringAsync().Result;
                        //已发送的验证码
                        Session["Mobile"] = mobile_code;//可以那此值与客户输入的验证码作比较。
                        return jj;
                    }
                    else
                    {
                        var jj = result.StatusCode;
                        return Newtonsoft.Json.JsonConvert.SerializeObject("code:1");
                    }
                }
            }
            else
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject("code:1");
            }
        }

        /// <summary>
        /// 显示主页
        /// </summary>
        /// <returns></returns>
        public ActionResult DefaultPage()
        {
            return View();
        }

        /// <summary>
        /// 主页 轮播
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowPage()
        {
            return View();
        }

        RolePermissionBll RpBll = new BLL.RolePermissionBll();
        /// <summary>
        /// 父级节点
        /// </summary>
        /// <returns></returns>
        public JsonResult Partent()
        {

            int RoleId = Convert.ToInt32(Session["RoleId"]);
            var Partent = RpBll.ShowRolePermission().Where(m => m.PermissionParentId == 0 && m.RoleId == RoleId).ToList();
            foreach (var tree in Partent)
            {
                PartentId(tree.PermissionId);//调用子节点
            }
            return Json(Partent);
        }

        /// <summary>
        /// 子级节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public JsonResult PartentId(int id)
        {

            int RoleId = Convert.ToInt32(Session["RoleId"]);
            var Partent = RpBll.ShowRolePermission().Where(m => m.PermissionParentId == id && m.RoleId == RoleId).ToList();
            return Json(Partent);
        }


        #endregion

        #region 分配权限

        PermissionBll perbll = new PermissionBll();
        RolePermissionBll rpbll = new RolePermissionBll();
        RoleBll rolebll = new RoleBll();

        /// <summary>
        /// 初始化分配权限页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AllotPermission()
        {
            var Permisson = perbll.ShowPermission();
            return View(Permisson);
        }

        /// <summary>
        /// 分配权限
        /// </summary>
        /// <returns></returns>
        public int AddPermisson()
        {

            if (Request["id"].Length > 0)
            {
                string str = Request["id"].Substring(0, Request["id"].Length - 1);
                string[] s = str.Split(',');
                int id = Convert.ToInt32(Request["selected"]);
                List<RolePermission> role = rpbll.ShowRolePermission().Where(x => x.RoleId == id).ToList();
                if (role.Count > 0)
                {
                    foreach (var m in role)
                    {
                        rpbll.DelRolePermission(m);
                    }
                }
                foreach (var i in s)
                {
                    var permisson = perbll.ShowPermission().Where(t => t.PermissionId == Convert.ToInt32(i)).FirstOrDefault();


                    RolePermission rolepermisson = new RolePermission();
                    rolepermisson.PermissionId = permisson.PermissionId;
                    rolepermisson.RoleId = Convert.ToInt32(Request["selected"]);
                    rolepermisson.PermissionName = permisson.PermissionName;
                    rolepermisson.PermissionUrl = permisson.PermissionUrl;
                    rolepermisson.PermissionParentId = permisson.PermissionParent;
                    RpBll.AddRolePermission(rolepermisson);
                }
                return 1;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 显示权限
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowPermission(int PageIndex=1)
        {
            int PageSize = 5;
            int PageCount = 0;
            var list = perbll.PaperPermission(PageIndex, PageSize, out PageCount);
            ViewBag.list = list;
            ViewBag.TotalPage = (int)Math.Ceiling((double)PageCount / (double)PageSize);
            ViewBag.PageIndex = PageIndex;
            ViewBag.PageSize = PageSize;
            return View();
        }

        /// <summary>
        /// 初始化添加权限视图
        /// </summary>
        /// <returns></returns>
        public ActionResult AddPermission()
        {
            return View(perbll.ShowPermission());
        }

        /// <summary>
        /// 实现添加权限
        /// </summary>
        /// <returns></returns>
        public bool AddPermissionDo()
        {
            Permission per = new Permission();
            per.PermissionName = Request["PermissionName"];
            per.PermissionUrl = Request["PermissionUrl"];
            per.PermissionParent = Convert.ToInt32(Request["ParentId"]);
            if (perbll.AddPermission(per))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 编辑权限页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UpdPermission(int id)
        {
            Permission m = perbll.BackPermission(id);
            var s = perbll.ShowPermission();
            ViewBag.s = s;
            return View(m);
        }

        /// <summary>
        /// 执行编辑权限操作
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UpdPermissiondo(Permission m)
        {
            if (perbll.UpdPermission(m,m.PermissionId))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <returns></returns>
        public bool PermissionDelete()
        {
            if (Request["id"].Length > 0)
            {
                string id = Request["id"].Substring(0, Request["id"].Length - 1);
                string[] s = id.Split(',');
                foreach (var i in s)
                {
                    Permission per = new Permission();
                    per.PermissionId = Convert.ToInt32(i);
                    perbll.DelPermission(per);
                }
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region  用户角色
        /// <summary>
        /// 添加用户页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddUser()
        {
            return View(rolebll.ShowRole());
        }

        /// <summary>
        /// 实现添加用户
        /// </summary>
        /// <returns></returns>
        public bool UserAdd()
        {
            UserInfo user = new UserInfo();
            user.UserName = Request["UserName"];
            user.UserPwd = Request["UserPwd"];
            user.UserPhone = Request["UserPhone"];
            user.RoleId = Convert.ToInt32(Request["RoleId"]);
            user.CreateDate = Convert.ToDateTime(DateTime.Now.ToString());
            if (bll.Register(user))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 显示用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowUser(int PageIndex=1)
        {
            int PageSize = 3;
            int PageCount = 0;
            var ulist = bll.ShowUserInfo(PageIndex,PageSize,out PageCount);
            var rlist = rolebll.ShowRole();
            var list = from s in ulist
                       join a in rlist on s.RoleId equals a.RoleId
                       select Tuple.Create( 
                           s.UserId,
                           s.UserName,
                           s.UserPwd,
                           s.UserPhone,
                           s.RoleId,
                           s.CreateDate,
                           a.RoleName);
            ViewBag.list = list;
            ViewBag.TotalPage = (int)Math.Ceiling((double)PageCount / (double)PageSize);
            ViewBag.PageIndex = PageIndex;
            ViewBag.PageSize = PageSize;
            return View();
        }

        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UpdUser(int id)
        {
            UserInfo m = bll.BackUser(id);
            var s = rolebll.ShowRole();
            ViewBag.s = s;
            return View(m);
        }

       /// <summary>
       /// 执行修改用户操作
       /// </summary>
       /// <param name="m"></param>
       /// <returns></returns>
        public bool UpdUserdo(UserInfo m)
        {
            if (bll.UpdUser(m,m.UserId))
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 删除用户
        /// </summary>
        /// <returns></returns>
        public bool UserDelete()
        {
            if (Request["id"].Length > 0)
            {
                string id = Request["id"].Substring(0, Request["id"].Length - 1);
                string[] s = id.Split(',');
                foreach (var i in s)
                {
                    UserInfo user = new UserInfo();
                    user.UserId = Convert.ToInt32(i);
                    bll.DelUser(user);
                }
                return true;
            }
            else
            {
                return false;
            }
        }
        public ActionResult UpdRole(int id)
        {
            Role m = rolebll.BackRole(id);
            return View(m);
        }
        public bool Upd(Role m)
        {
            if(rolebll.UpdRole(m,m.RoleId))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 添加角色页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddRole()
        {
            return View();
        }

        /// <summary>
        /// 实现添加角色
        /// </summary>
        /// <returns></returns>
        public bool RoleAdd()
        {
            Role rol = new Role();
            rol.RoleName = Request["RoleName"];
            if (rolebll.AddRole(rol))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <returns></returns>
        public bool RoleDelete()
        {
            if (Request["id"].Length > 0)
            {
                string id = Request["id"].Substring(0, Request["id"].Length - 1);
                string[] s = id.Split(',');
                foreach (var i in s)
                {
                    Role rol = new Role();
                    rol.RoleId = Convert.ToInt32(i);
                    rolebll.DelRole(rol);
                }
                return true;
            }
            else
            {
                return false;
            }
        }



        /// <summary>
        /// 显示角色
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowRole()
        {
            return View(rolebll.ShowRole());
        }
        public ActionResult collme()
        {
            return View();
        }
#endregion
    }
}
